//
//  ActivityListVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/8/4.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "ActivityListVC.h"
#import "ActivityDetailVC.h"
#import "activityCell.h"
@interface ActivityListVC ()<UITableViewDelegate,UITableViewDataSource>

@end

@implementation ActivityListVC
{
    UITableView *_tableview;
    
    NSDictionary *_responseDic;
    NSMutableArray *_responseArr;
    
    NSInteger _currentPage;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _responseArr = [NSMutableArray array];
    _currentPage = 1;
    [self requsetForActityListCurrentPage:_currentPage isFirst:YES];
    [self initTableView];
    _tableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}
- (void)requsetForActityListCurrentPage:(NSInteger)currentPage isFirst:(BOOL)isFirst{
    //参数
    NSDictionary *parameters = @{
                                 @"status": self.status,
                                 @"pageNum": @(currentPage),
                                 @"pageSize": @"10",
                                 };

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/activity/list.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        [_tableview.mj_header endRefreshing];
        _responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@<<<<>>>>",_responseDic);
        NSArray *temp = _responseDic[@"list"];
        NSString *error = _responseDic[@"code"];
        if (![_responseDic[@"code"] isEqualToString:@"0000"]) {

            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
            
        }else{
            if (isFirst) {
                if (temp.count == 0) {
                    [SVProgressHUD showImage:nil status:@"暂无数据"];
                }
                [_responseArr removeAllObjects];
            }
            [_responseArr addObjectsFromArray:temp];
            
            if (temp.count < 10) {
                [_tableview.mj_footer endRefreshingWithNoMoreData];
            }
            else {
                [_tableview.mj_footer endRefreshing];
            }
            //请求成功
            [_tableview reloadData];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求活动列表失败"];
    }];
}
- (void)initTableView{
    _tableview = [[UITableView alloc]initWithFrame:self.view.frame];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [self.view addSubview:_tableview];
    
    [self refreshDown];
    [self refreshLoadMore];
}
//下拉刷新
- (void)refreshDown{
    _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _currentPage = 1;
        [self requsetForActityListCurrentPage:_currentPage isFirst:YES];
    }];
}
//上提加载更多
- (void)refreshLoadMore{
    _tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _currentPage++;
        [self requsetForActityListCurrentPage:_currentPage isFirst:NO];
    }];
}
#pragma - mark UITableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _responseArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    activityCell *cell = [[NSBundle mainBundle]loadNibNamed:@"activityCell" owner:nil options:nil][0];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.title.text = _responseArr[indexPath.row][@"title"];
    cell.city.text = _responseArr[indexPath.row][@"destination"];
    NSString *timeStr = _responseArr[indexPath.row][@"stratTime"];
    timeStr = [timeStr substringToIndex:10];
    cell.time.text = timeStr;
    NSString *startStr = _responseArr[indexPath.row][@"stratTime"];
    startStr = [startStr substringToIndex:10];
    NSString *endStr = _responseArr[indexPath.row][@"endTime"];
    endStr = [endStr substringToIndex:10];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *starDate=[formatter dateFromString:startStr];
    NSDate *endDate=[formatter dateFromString:endStr];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned int unitFlags = NSCalendarUnitDay;
    NSDateComponents *times = [calendar components:unitFlags fromDate:starDate toDate:endDate options:0];
    cell.days.text = [NSString stringWithFormat:@"%ld%@",(long)[times day],@"天"];
    NSString *urlStr = _responseArr[indexPath.row][@"coverImgURL"];
    [cell.corveImage sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"默认图片"]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ActivityDetailVC *vc = [[ActivityDetailVC alloc]init];
    vc.status = self.status;
    vc.activityId = _responseArr[indexPath.row][@"id"];
    vc.activityHtmlUrlStr = _responseArr[indexPath.row][@"htmlUrl"];
    [self.navigationController pushViewController:vc animated:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
